package com.larly.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.larly.common.BaseResponse;
import com.larly.common.ResultUtils;
import com.larly.exception.ErrorCode;
import com.larly.exception.ThrowUtils;
import com.larly.model.domain.Notification;
import com.larly.model.domain.User;
import com.larly.model.dto.notification.NotificationCreateRequest;
import com.larly.model.dto.notification.NotificationSelectRequest;
import com.larly.model.vo.NotificationVO;
import com.larly.service.NotificationService;
import com.larly.service.UserService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/notification")
public class NotificationController {

    @Resource
    private NotificationService notificationService;

    @Resource
    private UserService userService;

    /**
     * 创建通知（内部调用，可限制权限）
     */
    @PostMapping("/create")
    public BaseResponse<Boolean> createNotification(@Valid @RequestBody NotificationCreateRequest dto) {
        boolean success = notificationService.createNotification(dto);
        return ResultUtils.success(success);
    }


    /**
     * 获取用户通知
     *
     * @param dto
     * @return
     */
    @PutMapping("/user")
    public BaseResponse<List<NotificationVO>> getUserNotification(@RequestBody NotificationSelectRequest dto) {
        ThrowUtils.throwIf(dto.getPageNum() == null, ErrorCode.PARAM_ERROR);
        QueryWrapper<Notification> notificationQueryWrapper = notificationService.buildQueryWrapper(dto);
        List<NotificationVO> notificationVOS = notificationService.queryUserNotification(notificationQueryWrapper, dto);
        return ResultUtils.success(notificationVOS);
    }

    /**
     * 批量标记通知为已读
     */
    @PutMapping("/mark-read")
    public BaseResponse<Boolean> markNotificationAsRead(HttpServletRequest request, @RequestBody List<Integer> notificationIds) {
        User loginUser = userService.getLoginUser(request);
        boolean success = notificationService.readBatchNotification(notificationIds, loginUser.getId());
        return ResultUtils.success(success);
    }

    /**
     * 查询未读通知数量
     */
    @GetMapping("/unread-count")
    public BaseResponse<Long> getUnreadCount(HttpServletRequest request) {
        long count = notificationService.getUnreadCount(request);
        return ResultUtils.success(count);
    }
}